package com.ymttest.datadriver;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ymt.core.tool.Logger;
import com.ymttest.database.model.YmtProductsInActivity;
import com.ymttest.database.sqlwapper.YmtCatalogsIWapper;
import com.ymttest.database.sqlwapper.YmtProductsInActivityWapper;
import com.ymttest.utils.JsonBeanHelper;
import com.ymttest.utils.YMTDateUtil;

public class CaseExecuteHelper {
	
	public static Object getPreviousVal(Map<Integer, JSONObject> beforeApiRet, Integer beforeId,String pathKey) throws Exception{
		if (beforeApiRet.get(beforeId)==null){
			throw new NullPointerException("before id ["+beforeId+"] is not exist.");
		}
		
		Object ret = null;
		
		JSONObject beforeRet = beforeApiRet.get(beforeId);
	
		//set value which is not in return message
		if (pathKey.contains("CatalogIds") && !beforeRet.has("CatalogIds")){
			List<String> CatalogList = new ArrayList<String>();
			new YmtCatalogsIWapper().selectCatalogsByProductId(beforeRet.getString("ProductID")).forEach(E->CatalogList.add(E.getsCatalogId()));
			beforeRet.put("CatalogIds", new JSONArray(CatalogList));
		}
		
		if (pathKey.contains("ProductInActivityId") && !beforeRet.has("ProductInActivityId")){
			String productId = beforeRet.getJSONObject("JsonBeanRequest").getString("ProductId");
			YmtProductsInActivityWapper ymtProductsInActivityWapper = new YmtProductsInActivityWapper();	
			YmtProductsInActivity productsInActivity = ymtProductsInActivityWapper.selectByProductId(productId);
			int productInActivityId = productsInActivity.getIproductinactivityid();
			beforeRet.put("ProductInActivityId", new JSONArray("["+productInActivityId+"]"));
		}	
		
		Logger.debug("Before api id:"+ beforeId +" and return value:"+ beforeApiRet.get(beforeId).toString());
		
		//get value
		if (JsonBeanHelper.isJsonBeanNodeExist(beforeRet, pathKey)){
			ret = JsonBeanHelper.getJsonBeanNodeObj(beforeRet, pathKey);
		}else{
			Logger.comment("Before api id:"+ beforeId +" and return value:"+ beforeApiRet.get(beforeId).toString());
			throw new NullPointerException("before id ["+beforeId+"] path of key ["+pathKey+"]is not exist.");
		}
		
		return ret;
		
	}
	
	
	public static JSONObject updateModelWithGlobalData(JSONObject jsonModel,Map<String, String> globalDataMap) throws JSONException{
		String strModel = jsonModel.toString();

		if(globalDataMap!=null){
			for(String k:globalDataMap.keySet()){
				//模板修改全局变量
				strModel=strModel.replaceAll("\\$\\{"+k+"\\}", globalDataMap.get(k));
			}
		}
		return new JSONObject(strModel);
	}
	
	
	public static String hostNameReverasl(String hostName){
		String[] vals = hostName.replace("\\", "").split("\\.");
		StringBuffer ret = new StringBuffer();
		for(int i=vals.length;i>0;i--){
			ret.append(vals[i-1]).append(".");
		}
		return ret.deleteCharAt(ret.length()-1).toString();
	}
	
	
	public static JSONObject updateModelWithData(JSONObject jsonModel,Map<String, String> updateDataMap,Map<Integer,JSONObject> beforeApiRet) throws Exception{
		if (updateDataMap!=null){
			for(String K:updateDataMap.keySet()){
			    String V = updateDataMap.get(K);
				if (V.contains(".")){
					String[] args1 = V.toString().split("\\.");
					Integer beforeId = Integer.parseInt(args1[0]);
					String pathKey = args1[1];
					
					Object previousVal = getPreviousVal(beforeApiRet,beforeId,pathKey);
					/*if (K.equals("cookies")){
						//cookies:10007.cookies
						Logger.debug("Cookies:" + previousVal.toString().replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\"", ""));
						apiCall.setCookies(previousVal.toString().replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\"", ""));
					}else{
						
					}*/
					
					JsonBeanHelper.updateJsonBean(jsonModel, K,previousVal);
				}else{
					//for date  -  productEndTime:#(d,10);
					if (V.contains("#")){
						String[] vString = V.replaceAll("\\#", "").replaceAll("\\(", "").replaceAll("\\)", "").split(",");
						JsonBeanHelper.updateJsonBean(jsonModel,K,YMTDateUtil.getBeforeOrNextDay(Integer.parseInt(vString[1])));
						
					}else{
						JsonBeanHelper.updateJsonBean(jsonModel, K, V);
					}
				}
			}
		}
		return jsonModel;
		
		
	}
}
